package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.test.SubjectAvtivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class parasActivity extends AppCompatActivity{


    static List<String> categoryList = new ArrayList<>();
    static List<String> depIdList = new ArrayList<>();
    static List<String> termList = new ArrayList<>();

    Spinner spinner1;
    Spinner spinner2;
    Spinner spinner3;
    Button button;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_subject_activity);
        spinner1 = findViewById(R.id.categorySpinner1);
        spinner2 = findViewById(R.id.deptIdSpinner1);
        spinner3 = findViewById(R.id.termIdSpinner1);
        button = findViewById(R.id.webParaButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(parasActivity.this, SubjectAvtivity.class);
                intent.putExtra("category","1");
                intent.putExtra("deptId","927");
                intent.putExtra("termId","74470");
                startActivity(intent);

//                intent.putExtra("category",spinner1.getSelectedItem().toString());
//                intent.putExtra("deptId",spinner2.getSelectedItem().toString());
//                intent.putExtra("termId",spinner2.getSelectedItem().toString());
            }
        });
        new FetchPageTask().execute(SubjectAvtivity.url);

    }


    private class FetchPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... voids) {
            //String url = "https://xkcts.ucas.ac.cn:8443/course/termSchedule";
            String url = voids[0];
            //String cookie = "SESSION=NTc5NDM5NWMtMTI4ZC00YTY1LTk2MDMtM2U5MTY1NWM1ZTU3";

            // 参数
            boolean isGraduate = true;
            int category = 3;
            String deptId = "985";
            int termId = 74470;
            String courseCode = "";
            String courseName = "";
            String courseAttribute = "";
            String isSummer = "";
            if(voids.length > 1){
                category = Integer.parseInt(voids[1]);
                deptId = voids[2];
                termId = Integer.parseInt(voids[3]);
            }

            // 构建查询字符串
            @SuppressLint("DefaultLocale") String query = String.format(
                    "?isGraduate=%b&category=%d&deptId=%s&termId=%d&courseCode=%s&courseName=%s&courseAttribute=%s&isSummer=%s",
                    isGraduate, category, deptId, termId, courseCode, courseName, courseAttribute, isSummer
            );

            // 完整URL
            String fullUrl = url + query;
            StringBuilder response = new StringBuilder();

            try {
                URL obj = new URL(fullUrl);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                // 设置请求方法为GET
                con.setRequestMethod("GET");
                // 在请求头中设置Cookie
                con.setRequestProperty("Cookie", SubjectAvtivity.cookie);
                // 获取响应码
                int responseCode = con.getResponseCode();
                Log.d("HTTP Response", "Response Code: " + responseCode);
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String inputLine;

                    while ((inputLine = in.readLine()) != null){
                        response.append(inputLine);
                    }
                    in.close();
//                    boolean startAppending = false;
//
//                    while ((inputLine = in.readLine()) != null) {
//                        if (!startAppending && inputLine.contains("rowspan")) {
//                            startAppending = true;
//                        }
//                        if (startAppending) {
//                            response.append(inputLine);
//                        }
//                    }
//                    in.close();
                } else {
                    Log.e("HTTP Response", "Error in response: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("HTTP Response", "Exception: " + e.getMessage());
            }
            //courses = analysis(response.toString());
            return response.toString();
        }

        private void analysis(String toString) {
            // 解析HTML
            Document doc = Jsoup.parse(toString);
            Elements categoryOptions = doc.select("select#category > option");

            for (Element option : categoryOptions) {
                categoryList.add(option.text());
            }
            // 解析 deptId
            Elements deptIdOptions = doc.select("select#deptId > option");
            for (Element option : deptIdOptions) {
                depIdList.add(option.text());
            }
            // 解析 termId
            Elements termIdOptions = doc.select("select[name=termId] > option");
            for (Element option : termIdOptions) {
                termList.add(option.text());
            }

        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            System.out.println(result);
            analysis(result);
            ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(parasActivity.this, android.R.layout.simple_spinner_item,categoryList);

            //ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.options1, android.R.layout.simple_spinner_item);
            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner1.setAdapter(adapter1);

            //ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,R.array.options2_default, android.R.layout.simple_spinner_item);
            ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(parasActivity.this, android.R.layout.simple_spinner_item,depIdList);
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner2.setAdapter(adapter2);

            spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    updateSpinner2Options(spinner1.getSelectedItem().toString(), spinner2);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // Do nothing
                }
            });

            //ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.options3, android.R.layout.simple_spinner_item);
            ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(parasActivity.this, android.R.layout.simple_spinner_item,termList);
            adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner3.setAdapter(adapter3);
            // 处理结果
            Log.d("HTTP Response", "Page Content: " + result);
        }
    }
    private void updateSpinner2Options(String selectedOption1, Spinner spinner2) {
        int optionsArrayId;
        switch (selectedOption1) {
            case "京内院系":
                optionsArrayId = R.array.options2_for_option1;
                break;
            case "研究所":
                optionsArrayId = R.array.options2_for_option2;
                break;
            case "京外学院":
                optionsArrayId = R.array.options2_for_option3;
                break;
            case "基地":
                optionsArrayId = R.array.options2_for_option4;
                break;
            default:
                optionsArrayId = R.array.options2_default;
                break;
        }
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, optionsArrayId, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter2);
    }
}
